<template>
  <div class="library-filter">
    <!-- 快速筛选标签 -->
    <div class="quick-filters">
      <div class="filter-section">
        <span class="filter-title">快速筛选:</span>
        <div class="filter-tags">
          <el-tag
            v-for="tag in quickFilters"
            :key="tag.key"
            :type="activeQuickFilters.includes(tag.key) ? 'primary' : 'info'"
            :effect="activeQuickFilters.includes(tag.key) ? 'dark' : 'plain'"
            size="small"
            class="filter-tag"
            @click="toggleQuickFilter(tag.key)"
          >
            {{ tag.label }}
          </el-tag>
        </div>
      </div>
    </div>

    <!-- 高级筛选 -->
    <el-collapse v-model="activeCollapse" class="advanced-filters">
      <el-collapse-item title="高级筛选" name="advanced">
        <div class="advanced-content">
          <!-- 分类筛选 -->
          <div class="filter-row">
            <label class="filter-label">分类:</label>
            <div class="filter-buttons">
              <el-button
                v-for="cat in categories"
                :key="cat.key"
                :type="filters.category === cat.key ? 'primary' : ''"
                :plain="filters.category !== cat.key"
                size="small"
                @click="updateFilter('category', cat.key)"
              >
                {{ cat.label }}
              </el-button>
            </div>
          </div>

          <!-- 状态筛选 -->
          <div class="filter-row">
            <label class="filter-label">状态:</label>
            <div class="filter-buttons">
              <el-button
                v-for="status in statusOptions"
                :key="status.key"
                :type="filters.status === status.key ? 'primary' : ''"
                :plain="filters.status !== status.key"
                size="small"
                @click="updateFilter('status', status.key)"
              >
                {{ status.label }}
              </el-button>
            </div>
          </div>

          <!-- 字数区间 -->
          <div class="filter-row">
            <label class="filter-label">字数:</label>
            <div class="filter-buttons">
              <el-button
                v-for="range in wordCountRanges"
                :key="range.key"
                :type="filters.wordCount === range.key ? 'primary' : ''"
                :plain="filters.wordCount !== range.key"
                size="small"
                @click="updateFilter('wordCount', range.key)"
              >
                {{ range.label }}
              </el-button>
            </div>
          </div>

          <!-- VIP状态 -->
          <div class="filter-row">
            <label class="filter-label">类型:</label>
            <div class="filter-buttons">
              <el-button
                v-for="vip in vipOptions"
                :key="vip.key"
                :type="filters.vip === vip.key ? 'primary' : ''"
                :plain="filters.vip !== vip.key"
                size="small"
                @click="updateFilter('vip', vip.key)"
              >
                {{ vip.label }}
              </el-button>
            </div>
          </div>

          <!-- 评分筛选 -->
          <div class="filter-row">
            <label class="filter-label">评分:</label>
            <div class="rating-filter">
              <el-rate
                v-model="filters.minRating"
                :max="5"
                show-score
                score-template="{value}分以上"
                @change="onRatingChange"
              />
            </div>
          </div>

          <!-- 标签筛选 -->
          <div class="filter-row">
            <label class="filter-label">标签:</label>
            <div class="tag-selector">
              <el-select
                v-model="filters.tags"
                multiple
                placeholder="选择标签"
                size="small"
                collapse-tags
                collapse-tags-tooltip
                :max-collapse-tags="3"
                style="width: 300px"
                @change="onTagsChange"
              >
                <el-option
                  v-for="tag in availableTags"
                  :key="tag"
                  :label="tag"
                  :value="tag"
                />
              </el-select>
            </div>
          </div>

          <!-- 排序方式 -->
          <div class="filter-row">
            <label class="filter-label">排序:</label>
            <div class="sort-selector">
              <el-radio-group v-model="filters.sortBy" size="small" @change="onSortChange">
                <el-radio-button
                  v-for="sort in sortOptions"
                  :key="sort.key"
                  :label="sort.key"
                >
                  {{ sort.label }}
                </el-radio-button>
              </el-radio-group>
            </div>
          </div>
        </div>
      </el-collapse-item>
    </el-collapse>

    <!-- 筛选结果统计和操作 -->
    <div class="filter-actions">
      <div class="filter-stats">
        <span class="active-filters" v-if="hasActiveFilters">
          已选择 {{ activeFiltersCount }} 个筛选条件
        </span>
      </div>
      <div class="action-buttons">
        <el-button size="small" @click="resetFilters">重置筛选</el-button>
        <el-button type="primary" size="small" @click="applyFilters">应用筛选</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import type { NovelCategory, NovelStatus } from '@/types'

interface FilterOptions {
  category: string
  status: string
  wordCount: string
  vip: string
  minRating: number
  tags: string[]
  sortBy: string
}

interface Props {
  availableTags: string[]
  modelValue: FilterOptions
}

interface Emits {
  (e: 'update:modelValue', value: FilterOptions): void
  (e: 'apply'): void
  (e: 'reset'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 响应式数据
const activeCollapse = ref<string[]>([])
const activeQuickFilters = ref<string[]>([])

// 本地筛选器状态
const filters = ref<FilterOptions>({ ...props.modelValue })

// 快速筛选选项
const quickFilters = ref([
  { key: 'free', label: '免费小说' },
  { key: 'completed', label: '完结小说' },
  { key: 'high-rating', label: '高分好评' },
  { key: 'new-book', label: '新书推荐' },
  { key: 'hot', label: '热门小说' },
  { key: 'vip', label: 'VIP专享' },
])

// 筛选选项配置
const categories = ref([
  { key: 'all', label: '全部' },
  { key: 'fantasy', label: '玄幻' },
  { key: 'urban', label: '都市' },
  { key: 'romance', label: '言情' },
  { key: 'historical', label: '历史' },
  { key: 'scifi', label: '科幻' },
  { key: 'mystery', label: '悬疑' },
  { key: 'military', label: '军事' },
  { key: 'game', label: '游戏' },
])

const statusOptions = ref([
  { key: 'all', label: '全部' },
  { key: 'ongoing', label: '连载中' },
  { key: 'completed', label: '已完结' },
  { key: 'paused', label: '暂停更新' },
])

const wordCountRanges = ref([
  { key: 'all', label: '不限' },
  { key: '0-100000', label: '10万字以下' },
  { key: '100000-500000', label: '10-50万字' },
  { key: '500000-1000000', label: '50-100万字' },
  { key: '1000000-99999999', label: '100万字以上' },
])

const vipOptions = ref([
  { key: 'all', label: '全部' },
  { key: 'free', label: '免费' },
  { key: 'vip', label: 'VIP' },
])

const sortOptions = ref([
  { key: 'updatedAt', label: '最新更新' },
  { key: 'rating', label: '评分最高' },
  { key: 'viewCount', label: '人气最高' },
  { key: 'favoriteCount', label: '收藏最多' },
  { key: 'wordCount', label: '字数最多' },
  { key: 'createdAt', label: '最新发布' },
])

// 计算属性
const hasActiveFilters = computed(() => {
  return (
    filters.value.category !== 'all' ||
    filters.value.status !== 'all' ||
    filters.value.wordCount !== 'all' ||
    filters.value.vip !== 'all' ||
    filters.value.minRating > 0 ||
    filters.value.tags.length > 0 ||
    filters.value.sortBy !== 'updatedAt'
  )
})

const activeFiltersCount = computed(() => {
  let count = 0
  if (filters.value.category !== 'all') count++
  if (filters.value.status !== 'all') count++
  if (filters.value.wordCount !== 'all') count++
  if (filters.value.vip !== 'all') count++
  if (filters.value.minRating > 0) count++
  if (filters.value.tags.length > 0) count++
  if (filters.value.sortBy !== 'updatedAt') count++
  return count
})

// 方法
const updateFilter = (key: keyof FilterOptions, value: string | number | string[]) => {
  (filters.value as any)[key] = value
  emit('update:modelValue', { ...filters.value })
}

const toggleQuickFilter = (key: string) => {
  const index = activeQuickFilters.value.indexOf(key)
  if (index > -1) {
    activeQuickFilters.value.splice(index, 1)
  } else {
    activeQuickFilters.value.push(key)
  }
  
  // 应用快速筛选逻辑
  applyQuickFilters()
}

const applyQuickFilters = () => {
  // 重置筛选器
  const newFilters = {
    category: 'all',
    status: 'all',
    wordCount: 'all',
    vip: 'all',
    minRating: 0,
    tags: [],
    sortBy: 'updatedAt',
  }

  activeQuickFilters.value.forEach(filter => {
    switch (filter) {
      case 'free':
        newFilters.vip = 'free'
        break
      case 'completed':
        newFilters.status = 'completed'
        break
      case 'high-rating':
        newFilters.minRating = 4
        break
      case 'new-book':
        newFilters.sortBy = 'createdAt'
        break
      case 'hot':
        newFilters.sortBy = 'viewCount'
        break
      case 'vip':
        newFilters.vip = 'vip'
        break
    }
  })

  filters.value = newFilters
  emit('update:modelValue', { ...filters.value })
}

const onRatingChange = (value: number) => {
  updateFilter('minRating', value)
}

const onTagsChange = (value: string[]) => {
  updateFilter('tags', value)
}

const onSortChange = (value: string) => {
  updateFilter('sortBy', value)
}

const resetFilters = () => {
  filters.value = {
    category: 'all',
    status: 'all',
    wordCount: 'all',
    vip: 'all',
    minRating: 0,
    tags: [],
    sortBy: 'updatedAt',
  }
  activeQuickFilters.value = []
  emit('update:modelValue', { ...filters.value })
  emit('reset')
}

const applyFilters = () => {
  emit('apply')
}

// 监听外部值变化
watch(
  () => props.modelValue,
  (newValue) => {
    filters.value = { ...newValue }
  },
  { deep: true }
)
</script>

<style lang="scss" scoped>
.library-filter {
  background: var(--bg-primary);
  border: 1px solid var(--border-color);
  border-radius: var(--radius-lg);
  padding: var(--spacing-lg);
  margin-bottom: var(--spacing-lg);
}

.quick-filters {
  margin-bottom: var(--spacing-lg);
  
  .filter-section {
    display: flex;
    align-items: center;
    gap: var(--spacing-md);
    flex-wrap: wrap;
    
    .filter-title {
      font-weight: 500;
      color: var(--text-primary);
      min-width: 80px;
    }
    
    .filter-tags {
      display: flex;
      gap: var(--spacing-sm);
      flex-wrap: wrap;
      
      .filter-tag {
        cursor: pointer;
        transition: all 0.3s ease;
        
        &:hover {
          transform: translateY(-1px);
        }
      }
    }
  }
}

.advanced-filters {
  margin-bottom: var(--spacing-lg);
  
  :deep(.el-collapse-item__header) {
    font-weight: 500;
    color: var(--text-primary);
  }
}

.advanced-content {
  padding-top: var(--spacing-md);
}

.filter-row {
  display: flex;
  align-items: center;
  margin-bottom: var(--spacing-lg);
  gap: var(--spacing-md);
  
  .filter-label {
    min-width: 80px;
    font-weight: 500;
    color: var(--text-primary);
  }
  
  .filter-buttons {
    display: flex;
    gap: var(--spacing-sm);
    flex-wrap: wrap;
    flex: 1;
  }
  
  .rating-filter,
  .tag-selector,
  .sort-selector {
    flex: 1;
  }
}

.filter-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: var(--spacing-md);
  border-top: 1px solid var(--border-color);
  
  .filter-stats {
    .active-filters {
      color: var(--text-secondary);
      font-size: var(--font-size-sm);
    }
  }
  
  .action-buttons {
    display: flex;
    gap: var(--spacing-sm);
  }
}

// 响应式设计
@media (max-width: 768px) {
  .filter-row {
    flex-direction: column;
    align-items: flex-start;
    
    .filter-label {
      min-width: auto;
      margin-bottom: var(--spacing-xs);
    }
    
    .filter-buttons,
    .rating-filter,
    .tag-selector,
    .sort-selector {
      width: 100%;
    }
  }
  
  .filter-actions {
    flex-direction: column;
    gap: var(--spacing-md);
    text-align: center;
  }
}
</style> 